package com.five.reader.service.impl;

import com.five.exception.BusinessException;
import com.five.pojo.ReadHistory;
import com.five.reader.mapper.ReadHistoryMapper;
import com.five.reader.service.ReadHistoryService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ReadHistoryServiceImpl implements ReadHistoryService {

    private final ReadHistoryMapper readHistoryMapper;

    /**
     * 添加阅读记录
     * @param readHistory 阅读记录信息
     * @return 添加结果
     */
    @Override
    @Transactional
    public boolean addReadHistory(ReadHistory readHistory) {
        try {
            // 参数验证
            if (readHistory == null) {
                throw new BusinessException("阅读记录信息不能为空");
            }
            if (readHistory.getReaderId() == null) {
                throw new BusinessException("读者ID不能为空");
            }
            if (readHistory.getNovelId() == null) {
                throw new BusinessException("小说ID不能为空");
            }
            if (readHistory.getChapterId() == null) {
                throw new BusinessException("章节ID不能为空");
            }
            if (readHistory.getReadTime() == null || readHistory.getReadTime() < 0) {
                throw new BusinessException("阅读时长不能为空且必须大于等于0");
            }

            // 设置创建时间
            if (readHistory.getCreateTime() == null) {
                readHistory.setCreateTime(LocalDateTime.now());
            }

            return readHistoryMapper.insert(readHistory) > 0;
        } catch (Exception e) {
            throw new BusinessException("添加阅读记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取读者的阅读记录
     * @param readerId 读者ID
     * @return 阅读记录列表
     */
    @Override
    public List<ReadHistory> getReadHistoryByReader(Long readerId) {
        try {
            if (readerId == null) {
                throw new BusinessException("读者ID不能为空");
            }
            return readHistoryMapper.selectByReaderId(readerId);
        } catch (Exception e) {
            throw new BusinessException("获取阅读记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取读者最近阅读记录
     * @param readerId 读者ID
     * @param limit 限制条数
     * @return 最近阅读记录列表
     */
    @Override
    public List<ReadHistory> getRecentReadHistory(Long readerId, Integer limit) {
        try {
            if (readerId == null) {
                throw new BusinessException("读者ID不能为空");
            }
            if (limit == null || limit <= 0) {
                limit = 10; // 默认返回10条
            }
            return readHistoryMapper.selectRecentByReaderId(readerId, limit);
        } catch (Exception e) {
            throw new BusinessException("获取最近阅读记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取读者对某本小说的阅读记录
     * @param readerId 读者ID
     * @param novelId 小说ID
     * @return 阅读记录列表
     */
    @Override
    public List<ReadHistory> getReadHistoryByReaderAndNovel(Long readerId, Long novelId) {
        try {
            if (readerId == null) {
                throw new BusinessException("读者ID不能为空");
            }
            if (novelId == null) {
                throw new BusinessException("小说ID不能为空");
            }
            return readHistoryMapper.selectByReaderAndNovel(readerId, novelId);
        } catch (Exception e) {
            throw new BusinessException("获取小说阅读记录失败: " + e.getMessage());
        }
    }

    /**
     * 删除阅读记录
     * @param id 阅读记录ID
     * @return 删除结果
     */
    @Override
    @Transactional
    public boolean deleteReadHistory(Long id) {
        try {
            if (id == null) {
                throw new BusinessException("阅读记录ID不能为空");
            }
            
            // 先检查记录是否存在
            ReadHistory existingRecord = readHistoryMapper.selectById(id);
            if (existingRecord == null) {
                throw new BusinessException("阅读记录不存在");
            }
            
            return readHistoryMapper.deleteById(id) > 0;
        } catch (Exception e) {
            throw new BusinessException("删除阅读记录失败: " + e.getMessage());
        }
    }

    /**
     * 统计读者总阅读时长
     * @param readerId 读者ID
     * @return 总阅读时长（分钟）
     */
    @Override
    public Integer getTotalReadTime(Long readerId) {
        try {
            if (readerId == null) {
                throw new BusinessException("读者ID不能为空");
            }
            Integer totalTime = readHistoryMapper.sumReadTimeByReaderId(readerId);
            return totalTime != null ? totalTime : 0;
        } catch (Exception e) {
            throw new BusinessException("统计阅读时长失败: " + e.getMessage());
        }
    }

    /**
     * 统计小说被阅读次数
     * @param novelId 小说ID
     * @return 阅读次数
     */
    @Override
    public Integer getNovelReadCount(Long novelId) {
        try {
            if (novelId == null) {
                throw new BusinessException("小说ID不能为空");
            }
            Integer readCount = readHistoryMapper.countReadByNovelId(novelId);
            return readCount != null ? readCount : 0;
        } catch (Exception e) {
            throw new BusinessException("统计小说阅读次数失败: " + e.getMessage());
        }
    }

    /**
     * 更新阅读记录（可选方法，如果业务需要）
     * @param readHistory 阅读记录信息
     * @return 更新结果
     */
    @Transactional
    public boolean updateReadHistory(ReadHistory readHistory) {
        try {
            if (readHistory == null || readHistory.getId() == null) {
                throw new BusinessException("阅读记录信息不能为空");
            }
            
            // 检查记录是否存在
            ReadHistory existingRecord = readHistoryMapper.selectById(readHistory.getId());
            if (existingRecord == null) {
                throw new BusinessException("阅读记录不存在");
            }
            
            return readHistoryMapper.update(readHistory) > 0;
        } catch (Exception e) {
            throw new BusinessException("更新阅读记录失败: " + e.getMessage());
        }
    }

    /**
     * 根据ID获取阅读记录详情
     * @param id 阅读记录ID
     * @return 阅读记录详情
     */
    public ReadHistory getReadHistoryById(Long id) {
        try {
            if (id == null) {
                throw new BusinessException("阅读记录ID不能为空");
            }
            ReadHistory readHistory = readHistoryMapper.selectById(id);
            if (readHistory == null) {
                throw new BusinessException("阅读记录不存在");
            }
            return readHistory;
        } catch (Exception e) {
            throw new BusinessException("获取阅读记录详情失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除读者的阅读记录
     * @param readerId 读者ID
     * @return 删除结果
     */
    @Transactional
    public boolean deleteReadHistoryByReader(Long readerId) {
        try {
            if (readerId == null) {
                throw new BusinessException("读者ID不能为空");
            }
            return readHistoryMapper.deleteByReaderId(readerId) > 0;
        } catch (Exception e) {
            throw new BusinessException("批量删除阅读记录失败: " + e.getMessage());
        }
    }
}